﻿using AutoMapper;
using MediatR;
using ProduceBasicData.Api.Application.Command.InvoiceAndReceiptManage;
using ProduceBasicData.Api.DTO.InvoiceAndReceiptDto;
using ProduceBasicData.Domain.InvoiceAndReceiptManage;

using ProduceBasicData.ErrorCode;
using ProduceBasicData.Infrastructure.Interface;

namespace ProduceBasicData.Api.Application.Handler.InvoiceAndReceiptManage
{
    /// <summary>
    /// 获取到票信息
    /// </summary>
    public class GetReceiptHandler : IRequestHandler<GetReceiptCommand, ApiPaging<ReceiptDto>>
    {
        private readonly IBaseRespository<Receipt> _receiptRepository;
        private readonly IMapper _mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="receiptRepository"></param>
        /// <param name="mapper"></param>
        public GetReceiptHandler(IBaseRespository<Receipt> receiptRepository, IMapper mapper)
        {
            _receiptRepository = receiptRepository;
            _mapper = mapper;
        }
        /// <summary>
        /// 处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ApiPaging<ReceiptDto>> Handle(GetReceiptCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiPaging<ReceiptDto>();

            try
            {
                // 获取基础查询（排除已删除的数据）
                var receipt = await _receiptRepository.GetAllAsync();
                var query = receipt.Where(x => x.Isdel == false);

                // 应用查询条件（如果有）
                if (!string.IsNullOrEmpty(request.Keyword))
                {
                    query = query.Where(x =>
                        x.InvoiceNo != null && x.InvoiceNo.Contains(request.Keyword));
                }

                // 获取总记录数
                result.TotalCount = query.Count();

                // 执行分页查询
                if (result.TotalCount > 0)
                {
                    // 应用分页
                    var pagedData = query.OrderByDescending(x => x.CreateTime)
                        .Skip((request.Index - 1) * request.Size)
                        .Take(request.Size)
                        .ToList();

                    // 映射到DTO
                    result.PageDatas = pagedData.Select(x => new ReceiptDto
                    {
                        Id = x.Id,
                        SytemNo = x.SytemNo,
                        ReceiptSubject = x.ReceiptSubject,
                        ReceiptDate = x.ReceiptDate,
                        InvoiceIssuer = x.InvoiceIssuer,
                        InvoiceNo = x.InvoiceNo,
                        IsBindPurchaseOrder = x.IsBindPurchaseOrder,
                        PurchaseCode = x.PurchaseCode,
                        PurchaseSubject = x.PurchaseSubject,
                        SupplierName = x.SupplierName,
                        PurchaseDate = x.PurchaseDate,
                        InboundStatus = x.InboundStatus,
                        PaidAmount = x.PaidAmount,
                        ReceivedAmount = x.ReceivedAmount,
                        Status = x.Status,
                        CreateName = x.CreateName,
                        CreateTime = x.CreateTime,
                        UpdateName = x.UpdateName,
                        UpdateTime = x.UpdateTime,
                        Isdel = x.Isdel
                    }).ToList();
                }
                else
                {
                    result.PageDatas = new List<ReceiptDto>();
                }

                result.Code = ApiEnum.Success;
                result.Msg = "查询成功";
            }
            catch (Exception ex)
            {
                // 记录日志（实际项目中应使用专门的日志组件）
                // logger.LogError(ex, "到票查询异常");

                result.Code = ApiEnum.Failed;
                result.Msg = $"查询异常: {ex.Message}";
                result.PageDatas = new List<ReceiptDto>();
            }

            return result;
        }
    }
}
